package com.fr71.project.dm.utils.pay_utils;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

public class AliPayUtil {

    private static final Logger logger = LoggerFactory.getLogger(AliPayUtil.class);

    //APPID 支付宝支付配置
    //private static final String APPID = "2021004141620075";
    private static final String APPID = "";

    //私钥    支付宝支付配置
    //private static final String PK = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC55MlTulIxvpTIa9L5l9vNGjTbd0q/mP42slwowJYPOoSBdkNlrAC5hCzKYjn41Ggc2N5jazq4zaaJiIv/j1qywNCl5UYEQuaZrHFbOa2R/KmTeJUwgUQOkFraPcO7DrvZCwn01rdosYX8cjoh24GzroGG9fOAX8cy4Be9Md9d2wsVRMOGyWBgUqV3WaWFHk25AKtlbhrmOwKvhLZH/oZhqUG0fk50V+fIwd3GPH9Gmybi5J3zgF2Qp0aV0y7CBe1ccJcqByW1w0m0dKOGFlXUjZowBoZtilLzEEFtHIeMenblYKU4txg1Upih5VS0OMYAO/JoQUegwyqvKRRVe10nAgMBAAECggEAWTIUAB7IzaGalkhWZPieuN04O44TybdJU0lluxAdcJUte0kZsbFEb7+iFkHneyPACQduPdn3xTC4Fgn00t0gMeEevFs0q1rGdzos8g7M392SKHaVbz63Px242jsErb62F8CaOGbGfm+f0K+mgRRoOaUj9XQSMKjEVf78pQVHHiro2WbH01rTXR/ItwLN2Rz6VhE2iMqaur+Lza0QHrdBTzkL1cLRpCcD/2zSYHFwtjEg4lXaO4aIPPJsNJ9leRUkBaIo/j/8LSdhTMTdV20foSV3WZwTi+1Mk6YTpTdC0LOrQiOHMQaEGVLTWTk/Zg42AnxL2c2Gx957ZP92Bfv3oQKBgQDdePkWNvrCMjpOhIBwaZogn2CD+emU4PA3vYZpdoGx8NWIm/AORbhCq0SDq/ZVcbdGpXtHYBBGooKwW9V/Kz67mtIOI1qXwAQxiI7pTYrzaqm29mVXIIfFOYuFE3sDuU7WkLgvWpgn6D5bMaNrncx8RxNOdsLQXgjDDLHimvcurwKBgQDW39omVXfH4NxbxyKyZbCY/do11FTFzVQ/f1AibA58wkhK7RgQvr7W/9FBDQF+SejIyDVgyivaqLIAeTunaVzp3ZLjfB+hoq4PVEZss1KE/oCUkysZYqhyEgFUl2nMT+bmmtfDxZ53Kkse6No9G5ZonuCXIPHJIYC5X7geOjcXCQKBgQCuyydsDQBj/FhgV9s23WGzlZYLE1bzFYUBuSc4XTuHQNiG9OvFl+kRVTLB6RqF3TYVH83oSz0NQn16yz/5Ghxs3IgkeGqrkfS9U1XXdEfSTcCckmLxHM+LLRucb/+KtNowJg/377xe4sE0ID0mVmhpPX9TUg/3e//WUVKj0kJ8KQKBgQC9zkFiaU8EhdHBVJeGpKMpkdvGfwhfLfBEos6DiZYGiIvZe7QtXoEvZAxQ/Q8bomf5rDjShePVI/0QxAZ47G6BuxM81XEPk6dTrSsEbCbxierE03dX1jlbgiIguhtfuhkKDS+ZJKDFPNvcsu3M2uizA9z6QsSx2WFe3nnCYcQ2GQKBgQCJBUQ3q10PO2BRPLDgGMqhGtZQoRnv1gpyGius9NNW8fgpGLEKuTagkhRMtdhAmNIZbzxWjMe5ZxF00QomNox5aUuiLqqrKy2t+qpIxytTCtdfV/KgnF7gn0Z1cGAAAZy0pactk9h36hYlkwWouFBhpX/xycMsyEoe/E/83IQZWw==";
    private static final String PK = "";

    //支付宝公钥 支付宝支付配置
    //private static final String ALI_PUBLIC_KEY ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi0/AiPAMofXbD70uFeNZqOuYG3pJfjgNUkIOghqYKjfLZx4Kjb3AcJZP2L529tWZ8QvM88hAtCPRptMOEqI0bYWxs6vuZJWXtCvd2AupouLK7DK/EVpbvCbxwTjZHzSlbBe9CfU9LU7M80c282VRPrUSIZ+1K+VkWmr6kjhuQyIy/+jo+ZLlqrrWwR5/M4GpMX84bCk77bXtf3UekeLGjOHWhHPPkP+9qij84VEQENGvIMLoTHV5hXi+Q56f/g+BXASVstnXXB+hHhPuEyWADiuh9Ce1E48Hw9Bhy4/d2czBjTtyH97/+3X537vxplXkH53TSnZg2S5i9RyrDw1aqQIDAQAB";
    private static final String ALI_PUBLIC_KEY = "";

    // 支付宝支付配置
    //private static final String AES_KEY = "cNt6oxqpkUgUUW6P6XKI1w==";
    private static final String AES_KEY = "";

    private static AliPayUtil instance;

    private AliPayUtil() {
        // 1. 设置参数（全局只需设置一次）
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipay.com";
        config.signType = "RSA2";
        config.appId = APPID;
        config.merchantPrivateKey = PK;
        config.alipayPublicKey = ALI_PUBLIC_KEY;
        config.encryptKey = AES_KEY;
        Factory.setOptions(config);
    }

    public static synchronized AliPayUtil getInstance() {
        if (instance == null) {
            instance = new AliPayUtil();
        }
        return instance;
    }

    /**
     * 创建订单
     * @param tradeNo 订单号
     * @param noticeUrl 通知url
     * @param shopName 商品名称
     * @param price 金额
     * @return 支付url。空时异常 环境为手机时直接跳转该url可打开支付宝支付  电脑时生成二维码
     */
    public AlipayTradePrecreateResponse createOrder(String tradeNo, String noticeUrl, String shopName, int price) {
        try {
            AlipayTradePrecreateResponse resp = Factory.Payment.FaceToFace()
                    .asyncNotify(noticeUrl)
                    .preCreate(shopName, tradeNo, String.valueOf(price));

            if (ResponseChecker.success(resp)) {
                return resp;
            } else {
                logger.error("生成支付宝订单失败，{}，{}，{}", resp.code, resp.msg, resp.subMsg);
                return null;
            }
        } catch (Exception e) {
            logger.error("生成支付宝订单失败，{}", e.getMessage());
            return null;
        }
    }

    /**
     * 关闭订单
     */
    public boolean closeOrder(String tradeNo) {
        try {
            Factory.Payment.Common().close(tradeNo);
            return true;
        } catch (Exception e) {
            logger.error("关闭支付宝订单失败，{}", e.getMessage());
            return false;
        }
    }

    /**
     * 验签
     * @param map 回调参数
     * @return 验签是否成功
     */
    public boolean onPayResult(HashMap<String, String> map) {
        try {
            return Factory.Payment.Common().verifyNotify(map);
        } catch (Exception e) {
            logger.error("支付宝回调验签失败，{}", e.getMessage());
            return false;
        }
    }
}